package hz.mobileproject.pda.toolsmanager.activity;

import android.view.View;
import android.widget.ExpandableListView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_login_user;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.toolsmanager.adapter.ToolsCallAdapter;
import hz.mobileproject.pda.toolsmanager.bean.ToolData;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ToolCalling;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ToolsCallEnd;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ToolsCallList;
import hz.mobileproject.pda.toolsmanager.bean.request.RQ_ToolsCallStart;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_LoadCallList;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolInfo;
import hz.mobileproject.pda.toolsmanager.bean.response.RP_ToolSysSet;
import hz.mobileproject.pda.ui.base.BaseScanActivity;
import hz.mobileproject.pda.ui.view.ContentSummaryOtherDialog;
import hz.mobileproject.pda.ui.view.CustomListDialog;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_tools_call_v1)
public class ToolsCallV1Activity extends BaseScanActivity implements IShowBarcodeStr {
    @ViewInject(R.id.elv_tools)
    private ExpandableListView elv_tools;

    private ToolsCallAdapter mAdapter;
    private Gson mGson;
    //配置信息
    private RP_ToolSysSet mToolSystemSet;
    //扫码民警
    private Response_loadPoliceInfo mPoliceInfo;
    //开始检查获得检查id
    private String mCheckID;
    //已清点工具数
    private int mAlreadyCallToolsCount = 0;
    //已清点工位数
    private int mAlreadyCallStationsCount = 0;

    private static final int REQUEST_CODE_POLICE = 0x1011;
    private static final int REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS = 0x1015;

    @Override
    protected void initData() {
        setTitleText("工具清点");
        mAdapter = new ToolsCallAdapter(this);
        elv_tools.setAdapter(mAdapter);
        //去除父节点点击事件
        elv_tools.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        //全部展开
//        mAdapter.expandAllGroup(elv_tools);
        mGson = new Gson();
        //获取上一页传递的配置信息
        mToolSystemSet = (RP_ToolSysSet) getIntent().getSerializableExtra("key");
        scanPolice();
    }

    @Override
    protected void onScanSucesess(int requestCode, String scanMsg) {
        LogUtils.e(scanMsg);
        switch (requestCode) {
            case REQUEST_CODE_POLICE:
                getPliceInfoFromSer(scanMsg);
                break;
            case REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS:
                mScanLoadingDialog.dismiss();
                calling(scanMsg);
                break;
        }
    }


    @Event({R.id.btn_end_call})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.btn_end_call:
                endCalling();
                break;
        }
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
        scanStr = scanStr.indexOf("P") == 0 ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }

    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            mScanLoadingDialog.dismiss();

            Response_loadPoliceInfo loadPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (loadPoliceInfo == null) {
                ToastUtils.showLong("民警信息为空");
                return;
            }
            mPoliceInfo = loadPoliceInfo;

            startToolsCall();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取民警信息失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 调用开始清点接口
     */
    private void startToolsCall() {
        RQ_ToolsCallStart toolsCallStart = new RQ_ToolsCallStart();
        toolsCallStart.setCus_number(mPoliceInfo.getCus_number());
        toolsCallStart.setDept_id(mPoliceInfo.getDepartment_id());
        toolsCallStart.setDept_name(mPoliceInfo.getDepartment_name());
        toolsCallStart.setPerson_id(mPoliceInfo.getPolice_id());
        toolsCallStart.setPerson_name(mPoliceInfo.getPolice_name());
        toolsCallStart.setBegin_time(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        toolsCallStart.setCall_object(mToolSystemSet.getCall_object());
        toolsCallStart.setCall_leisure(mToolSystemSet.getCall_leisure());
        toolsCallStart.setBorrow_tool(mToolSystemSet.getBorrow_tool());
        toolsCallStart.setCredits(mToolSystemSet.getCredits());
        //调用开始清点接口
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_START, toolsCallStart, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                mCheckID = new JsonParser().parse(data).getAsJsonObject().get("check_id").getAsString();
                if (StringUtils.isEmpty(mCheckID)) {
                    ToastUtils.showLong("检查id为空，开始清点失败");
                    return;
                }
                //加载清点列表
                getCallListFromSer();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("开始清点失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("开始清点失败");
                LogUtils.e(ex);
            }
        });
    }


    /**
     * 加载清点列表
     */
    private void getCallListFromSer() {
        RQ_ToolsCallList rq_toolsCallList = new RQ_ToolsCallList();
        rq_toolsCallList.setCus_number(mPoliceInfo.getCus_number());
        rq_toolsCallList.setDept_id(mPoliceInfo.getDepartment_id());
        rq_toolsCallList.setCheck_id(mCheckID);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_QUERY_CALL_LIST, rq_toolsCallList, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                List<RP_LoadCallList> callList = mGson.fromJson(data, new TypeToken<ArrayList<RP_LoadCallList>>() {
                }.getType());
                mAdapter.clearAdd(callList);
                //全部展开
                mAdapter.expandAllGroup(elv_tools);
                if (callList == null || callList.size() == 0) {
                    ToastUtils.showLong("清点列表没有数据");
                    return;
                }
                //右上角清点清空显示设置
                int stationsSize = 0;
                for (int i = 0; i < callList.size(); i++) {
                    if (!"库存".equals(callList.get(i).getGroup_name())) {
                        stationsSize++;
                    }
                }
                int toolsSize = 0;
                for (int i = 0; i < callList.size(); i++) {
                    toolsSize = toolsSize + callList.get(i).getChildrenList().size();
                }

                final int finalStationsSize = stationsSize;
                final int finalToolsSize = toolsSize;

                setTitleRightIcon(true, R.mipmap.callnote);
                getIv_title_right().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String[] strs = {"工具总数：" + finalToolsSize + "，已清点工具数：" + mAlreadyCallToolsCount,
                                "工位总数：" + finalStationsSize + "，已清点完工位数：" + mAlreadyCallStationsCount};
                        CustomListDialog dialog = new CustomListDialog(ToolsCallV1Activity.this, strs);
                        dialog.show();
                    }
                });
                //获取列表之后
                scanAfterGetList();
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("加载清点列表(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("加载清点列表");
                LogUtils.e(ex);
            }
        });
    }


    private void calling(String scanMsg) {
        if (scanMsg.indexOf(mToolSystemSet.getStationPrefix()) == 0) {
            scanMsg = scanMsg.substring(2);
            //扫描的是工位
            for (int i = 0; i < mAdapter.getGroupCount(); i++) {
                RP_LoadCallList group = mAdapter.getGroup(i);
                if (scanMsg.equals(group.getStation_id())) {
                    mAdapter.setSelectGroup(elv_tools, i);
                    return;
                }
            }
            ToastUtils.showLong("清点列表无此工位");
        } else if (scanMsg.indexOf(mToolSystemSet.getToolPrefix()) == 0) {
            scanMsg = scanMsg.substring(2);
            //扫描的是工具
            if (mToolSystemSet.getCall_object() == RP_ToolSysSet.TSS_CALL_OBJECT_ONLY_TOOLS) {
                //如果是只需要清点工具
                for (int i = mAdapter.getmParentList().size() - 1; i >= 0; i--) {
                    RP_LoadCallList group = mAdapter.getGroup(i);
                    for (int j = group.getChildrenList().size() - 1; j >= 0; j--) {
                        ToolData toolData = group.getChildrenList().get(j);
                        if (scanMsg.equals(toolData.getTool_id())) {
                            //调用清点接口
                            callingToSer(group, toolData);
                            return;
                        }
                    }
                }
                ToastUtils.showLong("此工具不存在清点列表");
            } else {
                //先判断此工具是否在库存中  如果在直接清点
                for (int i = mAdapter.getmParentList().size() - 1; i >= 0; i--) {
                    RP_LoadCallList group = mAdapter.getGroup(i);
                    for (int j = group.getChildrenList().size() - 1; j >= 0; j--) {
                        ToolData toolData = group.getChildrenList().get(j);
                        if (scanMsg.equals(toolData.getTool_id()) && "库存".equals(group.getGroup_name())) {
                            //调用清点接口
                            callingToSer(group, toolData);
                            return;
                        }
                    }
                }
                if (mAdapter.getmSelectPosition() == -1) {
                    ToastUtils.showLong("请先扫描工位或使用人");
                    return;
                }
                RP_LoadCallList group = mAdapter.getGroup(mAdapter.getmSelectPosition());
                for (int i = group.getChildrenList().size() - 1; i >= 0; i--) {
                    ToolData toolData = group.getChildrenList().get(i);
                    if (scanMsg.equals(toolData.getTool_id())) {
                        //调用清点接口
                        callingToSer(group, toolData);
                        return;
                    }
                }
                ToastUtils.showLong("此工具不存在于当前工位或库存中");
            }
        } else {
            //扫的是使用人
            for (int i = 0; i < mAdapter.getGroupCount(); i++) {
                RP_LoadCallList group = mAdapter.getGroup(i);
                if (scanMsg.equals(group.getUser_id())) {
                    mAdapter.setSelectGroup(elv_tools, i);
                    return;
                }
            }
            ToastUtils.showLong("清点列表无此使用人");
        }
    }

    /**
     * 调用清点接口
     */
    private void callingToSer(final RP_LoadCallList group, final ToolData toolData) {
        RQ_ToolCalling rq_toolCalling = new RQ_ToolCalling();
        rq_toolCalling.setCus_number(toolData.getCus_number());
        rq_toolCalling.setCheck_id(mCheckID);
        rq_toolCalling.setDept_id(toolData.getDept_id());
        rq_toolCalling.setDept_name(toolData.getDept_name());
        rq_toolCalling.setPerson_id(mPoliceInfo.getPolice_id());
        rq_toolCalling.setPerson_name(mPoliceInfo.getPolice_name());
        rq_toolCalling.setTool_id(toolData.getTool_id());
        rq_toolCalling.setTool_name(toolData.getTool_name());
        rq_toolCalling.setTool_type(toolData.getTool_type());
        rq_toolCalling.setBorrow(toolData.getBorrow());
        rq_toolCalling.setStatus(RQ_ToolCalling.STATUS_ALREADY_CALL);
        rq_toolCalling.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        rq_toolCalling.setStation_id(group.getStation_id());
        rq_toolCalling.setStation_name(group.getStation_name());
        rq_toolCalling.setUser_id(group.getUser_id());
        rq_toolCalling.setUser_name(group.getUser_name());
        List<RQ_ToolCalling> callingList = new ArrayList<>();
        callingList.add(rq_toolCalling);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_CALLING, callingList, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                ToastUtils.showShort(group.getGroup_name()+"\n"+group.getStation_name()+"\n"+toolData.getTool_name());
                group.getChildrenList().remove(toolData);
                mAdapter.notifyDataSetChanged();
                mAlreadyCallToolsCount++;
                if (group.getChildrenList().size() <= 0) {
                    mAdapter.getmParentList().remove(group);
                    mAdapter.notifyDataSetChanged();
                    mAdapter.setmSelectPosition(-1);
                    mAlreadyCallStationsCount++;
                    scanAfterGetList();
                }
                if (mAdapter.getGroupCount() <= 0) {
                    //结束清点
                    endCalling();
                }
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showLong("清点失败(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showLong("清点失败");
                LogUtils.e(ex.toString());
            }
        });
    }

    private void endCalling() {
        final RQ_ToolsCallEnd rq_toolsCallEnd = new RQ_ToolsCallEnd();
        rq_toolsCallEnd.setCheck_id(mCheckID);
        rq_toolsCallEnd.setCus_number(mPoliceInfo.getCus_number());
        rq_toolsCallEnd.setDept_id(mPoliceInfo.getDepartment_id());
        if (mAdapter.getGroupCount() > 0) {
            rq_toolsCallEnd.setEnd_type(RQ_ToolsCallEnd.END_TYPE_ERRO);
            List<RQ_ToolCalling> tempList = new ArrayList<>();
            for (RP_LoadCallList loadCallList : mAdapter.getmParentList()) {
                for (ToolData toolData : loadCallList.getChildrenList()) {
                    RQ_ToolCalling rq_toolCalling = new RQ_ToolCalling();
                    rq_toolCalling.setCus_number(toolData.getCus_number());
                    rq_toolCalling.setCheck_id(mCheckID);
                    rq_toolCalling.setDept_id(toolData.getDept_id());
                    rq_toolCalling.setDept_name(toolData.getDept_name());
                    rq_toolCalling.setPerson_id(mPoliceInfo.getPolice_id());
                    rq_toolCalling.setPerson_name(mPoliceInfo.getPolice_name());
                    rq_toolCalling.setTool_id(toolData.getTool_id());
                    rq_toolCalling.setTool_name(toolData.getTool_name());
                    rq_toolCalling.setTool_type(toolData.getTool_type());
                    rq_toolCalling.setBorrow(toolData.getBorrow());
                    rq_toolCalling.setStatus(RQ_ToolCalling.STATUS_NOT_CALL);
                    rq_toolCalling.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
                    rq_toolCalling.setStation_id(loadCallList.getStation_id());
                    rq_toolCalling.setStation_name(loadCallList.getStation_name());
                    rq_toolCalling.setUser_id(loadCallList.getUser_id());
                    rq_toolCalling.setUser_name(loadCallList.getUser_name());
                    tempList.add(rq_toolCalling);
                }
            }
            rq_toolsCallEnd.setTool_array(tempList);
            ContentSummaryOtherDialog dialog = new ContentSummaryOtherDialog(this);
            dialog.setTitle("输入结束原因").setMessage("请输入结束原因描述").setOnClickListener(new ContentSummaryOtherDialog.OnClickListener() {
                @Override
                public void onPositiveClick(String s) {
                    rq_toolsCallEnd.setRemake(s);
                    HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_END, rq_toolsCallEnd, new CustomNetCallBack() {
                        @Override
                        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                            ToastUtils.showLong("结束清点成功");
                            ToolsCallV1Activity.this.finish();
                        }

                        @Override
                        public void onErrorFromSer(int rtnCode, String rtnMsg) {
                            ToastUtils.showLong("结束清点失败(" + rtnCode + "," + rtnMsg + ")");
                        }

                        @Override
                        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                            ToastUtils.showLong("结束清点成功");
                            LogUtils.e(ex.toString());
                        }
                    });
                }

                @Override
                public void onNagetiveClick() {

                }
            }).show();
        } else {
            rq_toolsCallEnd.setEnd_type(RQ_ToolsCallEnd.END_TYPE_NORMAL);
            rq_toolsCallEnd.setRemake("");
            rq_toolsCallEnd.setTool_array(new ArrayList<RQ_ToolCalling>());

            HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_TOOL_END, rq_toolsCallEnd, new CustomNetCallBack() {
                @Override
                public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                    ToastUtils.showLong("结束清点成功");
                    ToolsCallV1Activity.this.finish();
                }

                @Override
                public void onErrorFromSer(int rtnCode, String rtnMsg) {
                    ToastUtils.showLong("结束清点失败(" + rtnCode + "," + rtnMsg + ")");
                }

                @Override
                public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                    ToastUtils.showLong("结束清点成功");
                    LogUtils.e(ex.toString());
                }
            });
        }
    }


    /**
     * ====================================扫描流程=========================================
     */
    private void scanPolice() {
        //是否需要扫描民警
        if (RP_ToolSysSet.TSS_CALL_TYPE_SCAN_USER == mToolSystemSet.getCall_type()) {
            //扫民警
            openScan(REQUEST_CODE_POLICE, mToolSystemSet, "请扫描民警条码");
        } else if (RP_ToolSysSet.TSS_CALL_TYPE_LOGIN_USER == mToolSystemSet.getCall_type()) {
            //使用登录民警信息
            mPoliceInfo = new Response_loadPoliceInfo();
            Response_login_user loginUser = MainApp.getInstance().getLoginUser();
            mPoliceInfo.setCus_number(loginUser.getCus_number());
            mPoliceInfo.setDepartment_id(loginUser.getDepartment_id());
            mPoliceInfo.setDepartment_name(loginUser.getDepartment_name());
            mPoliceInfo.setPolice_code(loginUser.getPolice_code());
            mPoliceInfo.setPolice_id(loginUser.getPolice_id());
            mPoliceInfo.setPolice_name(loginUser.getPolice_name());
            startToolsCall();
        }
    }


    private void scanAfterGetList() {
        if (RP_ToolSysSet.TSS_SWEEP_TYPE_CAMERA == mToolSystemSet.getSweep_type()) {
            setTitleRightIcon(true, R.mipmap.scan_camera);
            getIv_title_right().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    openScan(REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS, mToolSystemSet, "请扫描条码");
                }
            });
        }
        //判断工具发放绑定方式
        switch (mToolSystemSet.getCall_object()) {
            case RP_ToolSysSet.TSS_CALL_OBJECT_ONLY_TOOLS:
                //扫描工具
                openScan(REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS, mToolSystemSet, "请扫描工具");
                break;
            case RP_ToolSysSet.TSS_CALL_OBJECT_WORKPOSITION:
                //扫描工位
                openScan(REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS, mToolSystemSet, "请扫描工位(库存工具直接扫描)");
                break;
            case RP_ToolSysSet.TSS_CALL_OBJECT_PERSON:
                //扫描使用人
                openScan(REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS, mToolSystemSet, "请扫描使用人(库存工具直接扫描)");
                break;
            case RP_ToolSysSet.TSS_CALL_OBJECT_PERSON_WORKPOSITION:
                //扫描工位或者使用人
                openScan(REQUEST_CODE_PRISONER_WORK_POSITION_TOOLS, mToolSystemSet, "请扫描工位或者使用人(库存工具直接扫描)");
                break;
        }
    }
}
